package com.dolphin.common.utils;

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hhwf on 2017/11/3.
 */
public class JWTUtil {

    private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";

    private static final String PAYLOAD = "payload";

    private static final String USERID = "userId";

    private static final String SUB = "sub";

    private static final String ISS = "iss";


    public static String sign(UserDTO userDTO) {
        try {
            final JWTSigner signer = new JWTSigner(SECRET);
            final Map<String, Object> claims = new HashMap<String, Object>();
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(userDTO);
            claims.put(PAYLOAD, jsonString);
            claims.put(USERID,userDTO.getUserid());
            return signer.sign(claims);
        } catch(Exception e) {
            return null;
        }
    }


    public static UserDTO unsign(String jwt) {
        final JWTVerifier verifier = new JWTVerifier(SECRET);
        try {
            final Map<String,Object> claims= verifier.verify(jwt);
            if (claims.containsKey(PAYLOAD)&&claims.containsKey(USERID)) {
                String json = (String)claims.get(PAYLOAD);
                String userId = claims.get(USERID).toString();
                ObjectMapper objectMapper = new ObjectMapper();
                UserDTO userDTO = objectMapper.readValue(json,UserDTO.class);
                if (userId.equals(userDTO.getUserid().toString())){
                    return userDTO;
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }


    public static void main(String[] args) {
        UserDTO userDTO = new UserDTO();
        userDTO.setUserid(1L);
        String sign = JWTUtil.sign(userDTO);
        System.out.println(sign);
        String str = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjoie1widXNlcmlkXCI6MX0iLCJ1c2VySWQiOjF9.FqLT-RbA48hn6Ah9Jsz-u6m6HZPJAjZ3aCv5nn9K3hg";
        UserDTO unsign = JWTUtil.unsign(str);
        System.out.println(unsign.getUserid());

    }

}
